<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        span {
            width: 150px;
            height: 150px;
            position: absolute;
            top: 200px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button id="make">点击到1000</button>
    <button id="back">点击500</button>
    <div></div>
    <span></span>
    <script>
        //获取元素
        var div = document.querySelector('div')
        var sp = document.querySelector('span')
        var make = document.querySelector('#make')
        var back = document.querySelector('#back')
        //  var timer= setInterval(() => {
        //      if (div.offsetLeft==400) {
        //         clearInterval(timer)
        //      }
        //     div.style.left=div.offsetLeft+1+'px';
        //   }, 30);
        //   封装动画
        function times(obj, target,callback) {
            // 为防止多次点击停不下来
            clearInterval(obj.timer)
            // 为了防止取不到整数需要做一下处理
            var step = (target - obj.offsetLeft) / 10
            // 用三元表达式处理
            step = step > 0 ? Math.ceil(step) : Math.floor(step)
            obj.timer = setInterval(() => {
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer)
                    if (callback) {
                        //调用函数
                        callback();
                    }
                } else {
                    obj.style.left = obj.offsetLeft + step + 'px';
                }
            }, 30);
        }
        make.addEventListener('click', function () {
            // 执行一个回调函数来把盒子颜色改变
            times(div, 1000,function(){
                // alert('你好嘛')
                div.style.backgroundColor='red'
            })
        })
        back.addEventListener('click', function () {
            times(div, 500)
        })
    </script>
</body>

</html>